// pages/time-report/time-report.js
const app = getApp()

Page({
  data: {
    taskId: null,
    taskInfo: null,
    isTiming: false,
    startTime: null,
    currentTime: null,
    elapsedTime: 0,
    timer: null,
    loading: true
  },

  onLoad: function (options) {
    if (options.task_id) {
      this.setData({
        taskId: options.task_id
      })
      this.loadTaskInfo()
    }
  },

  onUnload: function () {
    if (this.data.timer) {
      clearInterval(this.data.timer)
    }
  },

  loadTaskInfo: function () {
    app.request({
      url: '/getTimeTasks',
      method: 'GET'
    }).then((res) => {
      if (res.code === 1) {
        const tasks = res.data || []
        const taskInfo = tasks.find(task => task.id == this.data.taskId)
        if (taskInfo) {
          this.setData({
            taskInfo: taskInfo,
            loading: false
          })
        } else {
          wx.showToast({
            title: '任务不存在',
            icon: 'none'
          })
        }
      }
    }).catch((err) => {
      console.error('加载任务信息失败:', err)
    })
  },

  startTiming: function () {
    const now = new Date()
    this.setData({
      isTiming: true,
      startTime: now,
      currentTime: now,
      elapsedTime: 0
    })

    const timer = setInterval(() => {
      const currentTime = new Date()
      const elapsedTime = Math.floor((currentTime - this.data.startTime) / 1000)
      this.setData({
        currentTime: currentTime,
        elapsedTime: elapsedTime
      })
    }, 1000)

    this.setData({ timer: timer })
  },

  stopTiming: function () {
    if (this.data.timer) {
      clearInterval(this.data.timer)
    }
    this.setData({
      isTiming: false,
      timer: null
    })
    this.submitTimeReport()
  },

  submitTimeReport: function () {
    const hours = (this.data.elapsedTime / 3600).toFixed(2)
    const now = new Date()
    const workDate = now.toISOString().split('T')[0]
    
    app.request({
      url: '/submitTimeReport',
      method: 'POST',
      data: {
        tallocationtime_id: this.data.taskId,
        work_date: workDate,
        start_time: this.data.startTime.toISOString(),
        end_time: this.data.currentTime.toISOString(),
        total_hours: hours,
        remark: '小程序计时报工'
      }
    }).then((res) => {
      if (res.code === 1) {
        wx.showToast({
          title: '计时记录已提交',
          icon: 'success'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      }
    }).catch((err) => {
      console.error('提交计时记录失败:', err)
    })
  },

  // 格式化时间
  formatTime: function (seconds) {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60
    
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  },

  // 返回上一页
  goBack: function () {
    wx.navigateBack()
  }
})
